import React, {useEffect, useState, memo} from 'react';
import {Button, Col,  message, Row, Spin, Transfer} from "antd";
import {getAllUser} from "../../../../api/user"
import {getUsersBySystemId, modifyUsersBySystemId} from "../../../../api/system"


function EditUrls(props) {
    const {id} = props
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true)
    const [targetKeys, setTargetKeys] = useState([]);
    const onChange = (newTargetKeys) => {
        setTargetKeys(newTargetKeys);
    };

    const saveUsers = () => {
        setLoading(true)
        modifyUsersBySystemId({id: id * 1, ids: targetKeys}).then(response => {
            const {data: res} = response
            message.success(res.msg)
            setLoading(false)
        })
    }
    useEffect(() => {
        setLoading(true)
        async function getUsers() {
            const {data: res} = await getAllUser()
            return res.data
        }

        async function getCurrentUsers() {
            const {data: res} = await getUsersBySystemId(id)
            return res.data
        }
        getUsers().then(response => {
            let newData = []
            response.forEach(user => {
                newData.push({
                    id: user['id'],
                    username: user['username'],
                })
            })
            setData(newData)
        })
        getCurrentUsers().then(response => {
            setTargetKeys(response)
        })
        setTimeout(()=>{
            setLoading(false)
        },800)
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [id])
    return (
            <Spin tip="加载中..." spinning={loading}>
                    <Transfer
                        rowKey={record => record.id}
                        dataSource={data}
                        targetKeys={targetKeys}
                        onChange={onChange}
                        render={item => item.username}
                        pagination
                        showSearch
                        style={{padding:'0 5vh 0 5vh'}}
                    />
                    <Row>
                        <Col span={16}></Col>
                        <Col span={8} style={{
                            textAlign: 'right',
                        }}><Button type="primary" onClick={saveUsers}>保存</Button></Col>
                    </Row>
            </Spin>
    );
}

export default memo(EditUrls);